﻿using EntityFrameworkSample.DB;
using EntityFrameworkSample.DB.Model;
using EntityFrameworkSample.Migrations;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace EntityFrameworkSample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
                        
            InitialDbAsync()
                .ContinueWith<List<History>>(task =>
                {
                    using (var db = new BlogContext())
                    {
                        var histories = db.Database.SqlQuery<History>("select * from [dbo].[__MigrationHistory]").ToList();
                        return histories;
                    }
                }, TaskContinuationOptions.NotOnFaulted)
                .ContinueWith(task =>
                {
                    HistoryGrid.ItemsSource = ((Task<List<History>>)task).Result;
                    ProgressTextBlock.Text = "数据库更新完毕";
                    ProgressTextBlock.Visibility = Visibility.Collapsed;
                },
                CancellationToken.None,
                TaskContinuationOptions.NotOnFaulted,
                TaskScheduler.FromCurrentSynchronizationContext());
        }

        public Task InitialDbAsync()
        {
            return Task.Factory.StartNew(() =>
            {   
                Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());                                

                using (var db = new BlogContext())
                {
                    db.ContentTypes.FirstOrDefault();
                }
            });
        }       
    }
}
